<?php
namespace app\index\controller;


use think\Db;



class Index extends Home

{

    /**

    * 获取首页推荐活动,限制4个

    * 参数:null

    **/

    public function index()

    {

    	$data=Db::name('goxxaa1534488820_activity')->where(['setTop'=>1])->limit(4)->select();

        return json(0,"ok",$data);

    }



    /**

    * 获取首页图片和视频

    * 参数:null

    **/

    public function banner()

    {

        $data=Db::name('goxxaa1534488820_banner')->find();

        return json(0,"ok",$data);

    }

    /**

    * 获取所有相册

    * 参数:null

    **/
    public function getgallery()

    {
        $map['token']=['like','%goxxaa1534488820%'];

        $data=Db::name('photo')->where($map)->order('order asc')->select();

        if($data)
        {
            return json(0,"ok",$data);
        }else{
            return json(1,"暂无数据",null);
        }
    }

    /**

    * 获取某相册的照片

    * 参数:id,相册id,page:1

    **/
    public function getpics()

    {
        $page=input('page');

        $data=Db::name('photo_list')->where('pid = '.input('id'))->order('create_time desc')->paginate(10,false,['page'=>$page]);

        if($data->isEmpty())
        {
            return json(1,"暂无数据",null);
        }else{
            return json(0,"ok",$data);
        }
    }



    /**

    * 获取日程表信息，默认返回本周数据

    * 参数:date:某个周的一天2018-11-05,返回该周周一到周日的数据,page:1(默认)

    **/

    public function schedule()

    {

        $date=input('date');

        $startdate='';

        $dateline='';

        if(empty($date))

        {

            $startdate=strtotime(date('Y-m-d 00:00:00',time()))-((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600;//当前周周一

            $dateline=strtotime(date('Y-m-d 23:59:59',time()))+(7-(date('w') == 0 ? 7 : date('w'))) * 24 * 3600;//当前周周日

        }else{

            $startdate=strtotime($date.'00:00:00')-((date('w',strtotime($date)) == 0 ? 7 : date('w',strtotime($date))) - 1) * 24 * 3600;

            //某周一

            $dateline=strtotime($date.'23:59:59')+(7-(date('w',strtotime($date)) == 0 ? 7 : date('w',strtotime($date)))) * 24 * 3600;

            //某周日

        }

        $page=input('page');

        if(empty($page))

        {

            return json(1,'page不能为空',null);

        }

        $map['startTime']=["between",[$startdate,$dateline]];

        $data=Db::name('goxxaa1534488820_activity')->where($map)->paginate(10,false,['page'=>$page]);

        if($data->isEmpty())

        {

            return json(1,'暂无数据',null);

        }

        return json(0,'ok',$data);

    }



    /**

    * 获取某条活动的详情

    * 参数:acid:活动id

    **/

    public function getactivity()

    {

        $id=input('acid');

        if(empty($id))

        {

            return json(1,'活动id不能为空',null);

        }

        $active=Db::name('goxxaa1534488820_activity')->where(['aid'=>$id])->find();

        if(empty($active))

        {

            return json(1,'未找到该活动',null);

        }

        return json(0,'ok',$active);

    }



    /**

    * 报名某条活动

    * 参数:acid:活动id,number:订单数,没传默认为1,openid:微信openid，name:名字,telnum:电话

    **/

    public function signUpActive()

    {

        $id=input('acid');

        $number=input('num');

        $openid=input('openid');

        $name=input('name');

        $telnum=input('telnum');

        if(empty($id))

        {

            return json(1,'活动id不能为空',null);

        }

        if(empty($number)) 

        {

            $number=1;

        }

        if(empty($openid)) 

        {

            return json(1,'openid不能为空',null);

        }

        if(empty($name))

        {

            return json(1,'报名者姓名不能为空',null);

        }

        if(empty($telnum))

        {

            return json(1,'报名者电话不能为空',null);

        }

        $active=Db::name('goxxaa1534488820_activity')->where(['aid'=>$id])->find();

        if(empty($active))

        {

            return json(1,'未找到该活动',null);

        }

        $od=Db::name('goxxaa1534488820_order')->where(['aid'=>$active['aid'],'openid'=>$openid])->find();

        if(!empty($od))

        {

            return json(1,'您已经报过名了',null);

        }

        $count=Db::name('goxxaa1534488820_order')->where(['aid'=>$active['aid']])->sum('number');
        
        if((int)$active['maxtotal']!=0)
        {
            if($count>=$active['maxtotal'])
            {
                return json(1,'该活动报名人数已达上限',null);
            }
            $nm=(int)$active['maxtotal']-(int)$count;
            if($nm<$number)
            {
                return json(1,'活动名额仅剩'.$nm.'人,请从新选择报名人数',null);
            }
        }
        

        $order['state']=1;

        $order['aid']=$active['aid'];

        $order['number']=$number;

        $order['unitPrice']=$active['price'];

        $order['time']=time();

        $order['openid']=$openid;

        $order['name']=$name;

        $order['telnum']=$telnum;        

        $oid=Db::name('goxxaa1534488820_order')->insertGetId($order);

        return json(0,'报名成功',$oid);

    }



    /**

    * 会员签入

    * 参数:mobile:会员手机,openid:微信openid

    **/

    public function vipSignIn()

    {

        $mobile=input('mobile');

        $openid=input('openid');

        if(empty($mobile))

        {

            return json(1,'手机号不能为空',null);

        }

        if(empty($openid))

        {

            return json(1,'openid不能为空',null);

        }

        $vip=Db::name('goxxaa1534488820_vip')->where(['tel'=>$mobile])->find();

        if(empty($vip))

        {

            return json(1,'该手机号并非会员',null);

        }

        if(!$vip['openid'])

        {

            //没有openid则保存openid

            $nvip=Db::name('goxxaa1534488820_vip')->where(['vid'=>$vip['vid']])->update(["openid"=>$openid]);

            Db::name('goxxaa1534488820_user')->where(['tel'=>$mobile])->update(["type"=>1]);

            return json(0,'ok',$nvip);

        }else{

            //有openid时判断当前传入的openid是否跟已存在的openid一样，不一样则判断为不是会员

            if($vip['openid']!=$openid)

            {

                return json(2,'当前微信并未与该手机号绑定',null);

            }

        }

        Db::name('goxxaa1534488820_user')->where(['tel'=>$mobile])->update(["type"=>1]);

        return json(0,'ok',$vip);

    }



    /**

    * 查看我的报名

    * 参数:openid,page:1

    **/

    public function showMysign()

    {

        $openid=input('openid');

        $page=input('page');

        if(empty($openid)) 

        {

            return json(1,'openid不能为空',null);

        }

        if(empty($page))

        {

            return json(1,'page不能为空',null);

        }

        $od=Db::name('goxxaa1534488820_order o')->where(['openid'=>$openid])->join('tp_goxxaa1534488820_activity a','a.aid = o.aid','LEFT')->field('o.*,a.title,a.startTime,a.endTime,a.address,a.cover')->paginate(10,false,['page'=>$page]);;

        if($od->isEmpty())

        {

            return json(1,'暂无数据',null);

        }

        return json(0,'ok',$od);

    }



    /**

    * 判断是否已经登录过了

    * 参数：code,wx.login的code

    **/

    public function wxjudgelogIn()

    {

        $code=input('code');

        if(empty($code))

        {

            return json(1,'微信登录失败,请重试',null);

        }

        $param = array(

            'appid' => config('appid'),

            'secret' => config('appsecret'),

            'js_code' => $code,

            'grant_type' => 'authorization_code'

        );

        $url = 'https://api.weixin.qq.com/sns/jscode2session';

        $data=$this->http($url,$param,'post');

        $data=json_decode($data,true);

        if($data['openid'])

        {

            $user=Db::name('goxxaa1534488820_user u')->where(['openid'=>$data['openid']])->find();

            if(empty($user))

            {

                return json(1,'未使用过',$data);

            }

            return json(0,'ok',$user);

        }else{

            return json(1,'微信登录失败,请重试',null);

        }

    }



    /**

    * 手机号解密

    * 参数：encryptedData,iv,session_key

    **/

     public function decryptedData()

     {

        include_once ("wxBizDataCrypt.php"); //引入wxBizDataCrypt.php文件

        $appid = config('appid');

        $sessionKey = input('session_key');

        $encryptedData= input('encryptedData');

        $iv = input('iv');

        $pc = new \WXBizDataCrypt($appid, $sessionKey);

        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {

            return json(0,'ok',$data);

        } else {

            return json(1,'解密失败,请重试',$errCode);

        }

     }



    /**
    * 微信登录

    * 根据code换session_key与openid

    * 参数：code,wx.login的code,nickname,tel,headimg,

    **/

    public function wxlogIn()

    {

        $code=input('code');

        $tel=input('tel');

        $nickname=input('nickname');

        $headimg=input('headimg');

        if(empty($code))

        {

            return json(1,'微信登录失败,请重试',null);

        }

        if(empty($tel))

        {

            return json(1,'用户电话不能为空',null);

        }

        if(empty($nickname))

        {

            return json(1,'用户名不能为空',null);

        }

        if(empty($headimg))

        {

            return json(1,'用户头像不能为空',null);

        }

        $param = array(

            'appid' => config('appid'),

            'secret' => config('appsecret'),

            'js_code' => $code,

            'grant_type' => 'authorization_code'

        );

        $url = 'https://api.weixin.qq.com/sns/jscode2session';

        $data=$this->http($url,$param,'post');

        $data=json_decode($data,true);

        if($data['openid'])

        {

            $user['openid']=$data['openid'];

            $user['tel']=$tel;

            $user['nickname']=$nickname;

            $user['headimg']=$headimg;

            $user['type']=0;

            $uid=Db::name('goxxaa1534488820_user')->insertGetId($user);

            if(empty($uid))

            {

                return json(1,'微信登录失败,请重试',null);

            }

            return json(0,'ok',$user);

        }else{

            return json(1,'微信登录失败,请重试',null);

        }

    }



    /**

     * 发送HTTP请求方法

     * @param  string $url    请求URL

     * @param  array  $params 请求参数

     * @param  string $method 请求方法GET/POST

     * @return array  $data   响应数据

     */

    public function http($url, $params, $method = 'GET', $header = array(), $multi = false){

        $opts = array(

            CURLOPT_TIMEOUT        => 30,

            CURLOPT_RETURNTRANSFER => 1,

            CURLOPT_SSL_VERIFYPEER => false,

            CURLOPT_SSL_VERIFYHOST => false,

            CURLOPT_HTTPHEADER     => $header

        );

        /* 根据请求类型设置特定参数 */

        switch(strtoupper($method)){

            case 'GET':

                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);

                break;

            case 'POST':

                //判断是否传输文件

                $params = $multi ? $params : http_build_query($params);

                $opts[CURLOPT_URL] = $url;

                $opts[CURLOPT_POST] = 1;

                $opts[CURLOPT_POSTFIELDS] = $params;

                break;

            default:

                throw new Exception('不支持的请求方式！');

        }

        /* 初始化并执行curl请求 */

        $ch = curl_init();

        curl_setopt_array($ch, $opts);

        $data  = curl_exec($ch);

        $error = curl_error($ch);

        curl_close($ch);

        if($error) throw new Exception('请求发生错误：' . $error);

        return  $data;

    }



}

